package org.cypress.rtpack.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.cypress.rtpack.VO.arrPar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * API健康检查工具类
 */
public class APIChecker {
    private static final Logger logger = LoggerFactory.getLogger(APIChecker.class);

    // 私有构造方法防止实例化
    private APIChecker() {
        throw new AssertionError("不允许实例化工具类！");
    }

    /**
     * 检查API是否健康可用
     * @param url 要检查的API地址
     * @param decideStandard 判断标准：
     *     1. 不包含等号时，仅检查HTTP状态码是否为200
     *     2. 包含等号时（如"msg=success"），需验证JSON返回中对应字段值
     * @return 返回API是否健康的布尔值
     */
    public static arrPar IsAPIHealty(String url, String decideStandard, String assFunc) {
        arrPar retPar = new arrPar();

        HttpURLConnection connection = null;
        try {
            // 1. 创建HTTP连接
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            // 设置GET请求方式
            connection.setRequestMethod("GET");
            // 设置连接超时和读取超时均为5秒
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 2. 获取响应状态码
            int responseCode = connection.getResponseCode();

            // 情况1：判断标准不含等号，只需检查HTTP 200状态
            if (!decideStandard.contains("=")) {
                boolean isSuc = responseCode == HttpURLConnection.HTTP_OK;
                retPar.setVb(isSuc,0);
                return retPar;
            }

            // 情况2：判断标准包含等号，需要解析JSON响应体
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 使用Jackson解析JSON
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(response.toString());
                // 拆分判断标准（例如："msg=success"）
                String[] parts = decideStandard.split("=", 2);
                String key = parts[0];          // 获取JSON字段名
                String expectedValue = parts[1]; // 获取期望值

                // 验证JSON中是否存在指定字段且值匹配
                if (rootNode.has(key) && expectedValue.equals(rootNode.get(key).asText())) {
                    retPar.setVb(true,0);
                    if (assFunc.contains("|")){
                        String[] nab = assFunc.split("\\|",5);  //直接用|为正则用法  nab[0]为key_key
                        if (nab.length > 2){
                            String resBack = "";
                            String[] key_key = nab[0].split("\\.",5);
                            JsonNode cen_cen = rootNode;
                            for(int i = 0; i < key_key.length; i++){
                                cen_cen = cen_cen.get(key_key[i]);
                            }
                            resBack = cen_cen.asText();     //[urn:ZD-win10:ics:SCADA:RTDBServer]
                            int rs_th = 1;
                            for(int j = 1; j < nab.length; j++){
                                String[] pcnm_rscodes = nab[j].split(">");
                                if(resBack.contains(pcnm_rscodes[0])){
                                    int rs_type = -1;
                                    int s1 = 0;
                                    for(int k = 0; k < pcnm_rscodes[1].length(); k++){
                                        String carThis = pcnm_rscodes[1].substring(k,k+1);
                                        if (carThis.equals("r")){
                                            if(rs_type < 0) {
                                                rs_type = 0;
                                            }
                                        }
                                        else if (carThis.equals("s")){
                                            if(rs_type < 0) {  //为了兼容reset(91)写法
                                                rs_type = 1;
                                            }
                                        }
                                        else if (carThis.equals("(")){
                                            s1 = k + 1;
                                        }
                                        else if (carThis.equals(")")){
                                            if(rs_type >= 0){
                                                retPar.setVi(Integer.parseInt(pcnm_rscodes[1].substring(s1,k)),rs_th);
                                                retPar.setVb((rs_type == 1),rs_th);
                                                rs_th++;
                                            }
                                            rs_type = -1;
                                        };
                                    }
                                }
                            }
                        }

                    }
                    return retPar;
                }
            }
            return retPar;
        } catch (Exception e) {
            // 发生任何异常都视为不健康
            return retPar;
        } finally {
            // 确保关闭连接释放资源
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
